package com.sunday.common.mq.rabbit.brave.autoconfiguration;

import brave.spring.rabbit.SpringRabbitTracing;
import brave.spring.rabbit.TracingRabbitPostProcessor;
import com.sunday.common.mq.rabbit.brave.aspectj.TracingRabbitAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;

/**
 * 补全 rabbit pull 模式链路问题
 *
 * @author zsy
 * @since 2023/8/16
 */
@Slf4j
@AutoConfiguration(after = RabbitTemplate.class)
@ConditionalOnBean(SpringRabbitTracing.class)
public class RabbitTracingAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public TracingRabbitPostProcessor tracingAfterReceivePostProcessor(SpringRabbitTracing springRabbitTracing, RabbitTemplate rabbitTemplate) {
        TracingRabbitPostProcessor tracingRabbitPostProcessor = new TracingRabbitPostProcessor(springRabbitTracing);
        /**
         * Consumer Pull Brave
         */
        rabbitTemplate.addAfterReceivePostProcessors(tracingRabbitPostProcessor);
        return tracingRabbitPostProcessor;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnSingleCandidate(TracingRabbitPostProcessor.class)
    public TracingRabbitAspect tracingReceiveAspect(TracingRabbitPostProcessor tracingRabbitPostProcessor) {
        return new TracingRabbitAspect(tracingRabbitPostProcessor);
    }

}
